package com.myjob.serviceImpl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.myjob.config.Constants;
import com.myjob.entity.Blog;
import com.myjob.entity.Comment;
import com.myjob.mapper.BlogMapper;
import com.myjob.mapper.CommentMapper;
import com.myjob.response.Result;
import com.myjob.service.CommentService;
import com.myjob.utils.UtilValidate;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

/**
 * @author Chen Yuan
 * @create 2021-01-21  19:16
 */
@Service
@Slf4j
public class CommentServiceImpl implements CommentService {
	@Autowired
	private CommentMapper commentMapper;
	@Autowired
	private BlogMapper blogMapper;

	/**
	 * 查询所有的评论
	 * @param blogId 被评论的博客编号
	 * @return
	 */
	@Override
	public List<List<Comment>> selectComments(String blogId) {
		if (UtilValidate.isEmpty(blogId)){
			return null;
		}
		List<Comment> commentList = getCommentList(blogId);
		List<List<Comment>> result = RebuildCommentList(commentList);
		return result;
	}

	@Override
	public Result selectCommentsByUser(String userId, String searchValue,
									   Integer currentPage, Integer pageSize) {
		QueryWrapper<Blog> blogWrapper = new QueryWrapper<>();
		blogWrapper.eq("user_id", userId);
		List<Blog> blogs = blogMapper.selectList(blogWrapper);

		if (UtilValidate.isEmpty(blogs)) {
			return Result.succeed(null, "没有发布文章");
		}

		List<String> collect = blogs.stream().map(Blog::getBlogId).collect(Collectors.toList());

		QueryWrapper<Comment> commentWrapper = new QueryWrapper<>();
		commentWrapper.in("blog_id", collect);
		commentWrapper.eq("deleted", Constants.getNoDel());
		commentWrapper.orderByDesc("create_date");
		if (UtilValidate.isNotEmpty(searchValue)) {
			commentWrapper.and(w -> w.like("content", searchValue).
					or().like("user_name",searchValue));
		}
		Integer size = UtilValidate.isEmpty(pageSize) ? Constants.getPageSize() : pageSize;
		Page<Comment> page = new Page<>(currentPage, size);
		IPage<Comment> commentIPage = commentMapper.selectPage(page, commentWrapper);
		return Result.succeed(commentIPage, "查询成功");
	}

	/**
	 * 新增评论
	 * @param comment 评论内容
	 * @return 影响行数
	 */
	@Override
	public int addComment(Comment comment) {
		if (UtilValidate.isEmpty(comment)){
			return -1;
		}
		return commentMapper.insert(comment);
	}

	/**
	 * 删除评论
	 * @param CommentId 评论编号
	 * @return 影响行数
	 */
	@Override
	public int deleteComment(String CommentId) {
		if (UtilValidate.isEmpty(CommentId)){
			return -1;
		}
		Comment comment = commentMapper.selectById(CommentId);
		if (UtilValidate.isEmpty(comment)){
			return -1;
		}
		String commentId = comment.getCommentId();
		String parentId = comment.getParentId();
		commentMapper.updateCommentsByParent(commentId, parentId);
		int row = 0;
		if (Objects.equals(comment.getDeleted(), Constants.getNoDel())){
			// 逻辑删除
			comment.setDeleted(Constants.getYetDel());
			row = commentMapper.updateById(comment);
		}else {
			// 物理删除
			row = commentMapper.deleteById(CommentId);
		}
		return row;
	}



	/**
	 * 获取评论列表
	 * @param blogId 博客编号
	 * @return
	 */
	private List<Comment> getCommentList(String blogId) {
		List<Comment> result = new ArrayList<>();
		QueryWrapper<Comment> wrapper = new QueryWrapper<>();
		wrapper.eq("deleted", Constants.getNoDel());
		wrapper.eq("blog_id", blogId);
		wrapper.orderByDesc("create_date");
		List<Comment> allComments = commentMapper.selectList(wrapper);

		Map<String, Comment> parentMap = new HashMap<>();

		for (Comment c : allComments) {
			if ("0".equals(c.getParentId())){
				result.add(c);
			}
			parentMap.put(c.getCommentId(), c);
		}
		for (Comment c : allComments) {
			if (!Objects.equals(c.getParentId(), "0")) {
				Comment parent = parentMap.get(c.getParentId());
				if (UtilValidate.isEmpty(parent.getChildList())) {
					parent.setChildList(new ArrayList<>());
				}
				parent.getChildList().add(c);
			}
		}
		return result;
	}

	/**
	 * 重构评论列表，将多重数组转为 2 维数组
	 * @param comments 待重构的列表
	 * @return
	 */
	public List<List<Comment>> RebuildCommentList(List<Comment> comments){
		ArrayList<List<Comment>> result = new ArrayList<>();
		for (Comment comment : comments) {
			ArrayList<Comment> temp = new ArrayList<>();
			DFS(comment, temp);
			System.out.println(temp);
			result.add(temp);
		}
		return result;
	}

	/**
	 * 深度优先遍历评论数组
	 * @param comment
	 * @param commentList
	 */
	public void DFS(Comment comment, List<Comment> commentList){
		if (UtilValidate.isEmpty(comment)) {
			return;
		}
		List<Comment> childList = comment.getChildList();
		comment.setChildList(null);
		commentList.add(comment);
		if (UtilValidate.isNotEmpty(childList) &&
				childList.size() > 0){
			for (Comment c : childList) {
				DFS(c, commentList);
			}
		}
	}
}
